'''
Created on Nov 6, 2009

@author: kage
'''
import sys, os

from PyQt4 import QtCore, QtGui

from PyBatch.uiFiles.mainwindow import Ui_MainWindow

from PyBatch.handlers.startup import Startup
from PyBatch.handlers.settings import Settings
from PyBatch.handlers.aboutPyBatch import AboutPyBatch
from converter import Converter

from PyBatch.handlers.queueItem import QueueItem
from PyBatch.handlers.fileQueue import FileQueue
        
class MainWindow(QtGui.QMainWindow):
    def __init__(self, script_dir, parent=None):   
        QtGui.QMainWindow.__init__(self, parent)
        self.__script_dir = script_dir
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initialiseGuiElements()
        self.initialiseParams()
        self.tieUpLooseEnds()
    
    def initialiseParams(self):
        self.vidQueue = FileQueue()
        self.audQueue = FileQueue()
        
        self.activeQueue = None
        self.activeGuiQueue = None
        self.converterMode = 'muxer'
        self.output = None
        self.totalJobs = None
        self.processedJobs = 0
        self.currentJob = None
        self.jobID = None
        self.abortFlag = False
        
        self.appConfig = None
        self.appStart = None
        self.logTxt = ''
        self.instanceArgs = {}
        self.appStart = Startup(os.path.join(self.__script_dir, "config.ini"), self.__script_dir)
        self.appConfig = self.appStart.appConfig['config']
        self.vidUtil = Converter(self.appConfig)
        self.settings = None
        self.aboutPyBatch = None
        self.Timer = QtCore.QTimer(self)
        self.elapsedTime = QtCore.QTime()
        self.estimatedTime = QtCore.QTime()
        
    def initialiseGuiElements(self):
        self.ui.audioModeOperation.setDisabled(True)
        
        #parma calc
        totalSize = self.ui.queue_Video.size()
        self.__queueHeader = ['Status', 'Filename']
        
        #video queue initialisation
        self.ui.queue_Video.setHorizontalHeaderLabels(self.__queueHeader)
        self.ui.queue_Video.setColumnWidth(0, 0.1 * totalSize.width())
        self.ui.queue_Video.setColumnWidth(1, 0.7 * totalSize.width())
        self.ui.queue_Video.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        self.ui.queue_Video.setAcceptDrops(1)
        self.ui.queue_Video.__class__.dragEnterEvent = self.fileDragEnterEvent
        self.ui.queue_Video.__class__.dragMoveEvent = self.fileDragEnterEvent
        self.ui.queue_Video.__class__.dropEvent = self.fileDropEvent
        
        #audio queue initialisation
        self.ui.queue_Audio.setHorizontalHeaderLabels(self.__queueHeader)
        self.ui.queue_Audio.setColumnWidth(0, 0.1 * totalSize.width())
        self.ui.queue_Audio.setColumnWidth(1, 0.7 * totalSize.width())
        self.ui.queue_Audio.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        self.ui.queue_Audio.setAcceptDrops(1)
        self.ui.queue_Audio.__class__.dragEnterEvent = self.fileDragEnterEvent
        self.ui.queue_Audio.__class__.dragMoveEvent = self.fileDragEnterEvent
        self.ui.queue_Audio.__class__.dropEvent = self.fileDropEvent
        
    def tieUpLooseEnds(self):
        con = QtCore.QObject.connect
        
        con(self.ui.addFiles, QtCore.SIGNAL("clicked()"), self.slotAddFiles)
        con(self.ui.addFolder, QtCore.SIGNAL("clicked()"), self.slotAddFolder)
        
        con(self.ui.audioMode, QtCore.SIGNAL("toggled(bool)") , self.ui.queue_Video.setDisabled)
        con(self.ui.audioMode, QtCore.SIGNAL("toggled(bool)") , self.ui.queue_Audio.setEnabled)
        
        con(self.ui.videoMode, QtCore.SIGNAL("toggled(bool)") , self.slotDisableAudQueue)
        con(self.ui.videoMode, QtCore.SIGNAL("toggled(bool)") , self.ui.queue_Video.setEnabled)
        
        con(self.ui.videoModeOperation, QtCore.SIGNAL("activated(int)"), self.slotDisableAudQueue)
        
        con(self.ui.queue_Video, QtCore.SIGNAL("cellDoubleClicked(int,int)"), self.slotUpdateInfo)
        con(self.ui.queue_Audio, QtCore.SIGNAL("cellDoubleClicked(int,int)"), self.slotUpdateInfo)
        
        con(self.ui.videoMode, QtCore.SIGNAL("toggled(bool)"), self.slotChooseMode)
        con(self.ui.videoModeOperation, QtCore.SIGNAL("currentIndexChanged(int)"), self.slotChooseMode)
        con(self.ui.audioModeOperation, QtCore.SIGNAL("currentIndexChanged(int)"), self.slotChooseMode)
        
        #tasks slots
        con(self.ui.startBatch, QtCore.SIGNAL("clicked()"), self.slotStartConversion)
        con(self.ui.outputFolder, QtCore.SIGNAL("clicked()"), self.slotCustomOutput)
        con(self.ui.defaultFolders, QtCore.SIGNAL("clicked(bool)"), self.slotDefaultOutput)
        con(self.ui.abortOperation, QtCore.SIGNAL("clicked()"), self.setAbortFlag)
        
        con(self.ui.removeSelected, QtCore.SIGNAL("clicked()"), self.slotRemoveFilesFromQueue)
        con(self.ui.removeAll, QtCore.SIGNAL("clicked()"), self.slotRemoveAll)
        
        #thread termination indicators
        con(self.vidUtil, QtCore.SIGNAL("finished()"), self.postJobOperations)
        con(self.vidUtil, QtCore.SIGNAL("terminated()"), self.postJobOperations)
        
        #menu actions slots
        con(self.ui.actionAddFiles, QtCore.SIGNAL("triggered()"), self.slotAddFiles)
        con(self.ui.actionAddFolder, QtCore.SIGNAL("triggered()"), self.slotAddFolder)
        con(self.ui.actionQuit, QtCore.SIGNAL("triggered()"), self.close)
        con(self.ui.actionRemoveAll, QtCore.SIGNAL("triggered()"), self.slotRemoveAll)
        con(self.ui.actionStartBatch, QtCore.SIGNAL("triggered()"), self.slotStartConversion)
        con(self.ui.actionPreferences, QtCore.SIGNAL("triggered()"), self.slotChangeAppConfig)
        con(self.ui.actionAbout, QtCore.SIGNAL("triggered()"), self.slotShowAboutPyBatch)
        
        #timer related slots
        con(self.Timer, QtCore.SIGNAL("timeout()"), self.slotUpdateElapsedtime)
        con(self.Timer, QtCore.SIGNAL("timeout()"), self.slotUpdateEstimatedTime)
        
    def log(self, data):
        self.logTxt += data + '\n'
        
    def printLogData(self):
        f = open(self.appConfig['logFile'])
    
    def closeEvent(self, event):
        self.appStart.saveConfig(self.appConfig)
        event.accept()
        
    def slotUpdateInfo(self, id, dummy):
        id = self.activeQueue.vals()[id]
        item = self.activeQueue.getItem(id)
        
        generalinfo = item.getGeneralInfo(self.appConfig)
        trackInfo = item.getTrackInfo(self.appConfig)
        
        #update general Info
        self.ui.fileName.setText(item.FileName)
        self.ui.fileFormat.setText(generalinfo['Format'])
        self.ui.fileSize.setText(generalinfo['Size'])
        self.ui.duration.setText(generalinfo['Duration'].split('.')[0])
        self.ui.defaultVideoID.setText(generalinfo['VideoID'])
        self.ui.defaultAudioID.setText(generalinfo['AudioID'])
        self.ui.defaultAudioLangage.setText(generalinfo['Language'])
        
        #update track Info
        self.ui.trackInfo_Source.setText(item.trackInfo)
        
    def slotDisableAudQueue(self):
        index = self.ui.videoModeOperation.currentIndex()
        if(index == 0):
            self.ui.queue_Audio.setEnabled(True)
        else:
            self.ui.queue_Audio.setDisabled(True)
        
    def slotAddFiles(self):
        if(self.ui.tabWidget_Queue.currentIndex() == 0 and self.ui.queue_Video.isEnabled()):
            self.activeQueue = self.vidQueue
            self.activeGuiQueue = self.ui.queue_Video
            filenames = QtGui.QFileDialog.getOpenFileNames(self, 'Select Files to add to the Queue', self.appConfig['inputFolder'], "Video Files (*.avi *.mp4 *.mkv *.ogm)")
        elif(self.ui.tabWidget_Queue.currentIndex() == 1 and self.ui.queue_Audio.isEnabled()):
            self.activeQueue = self.audQueue
            self.activeGuiQueue = self.ui.queue_Audio
            if(self.converterMode == 'audioExtractor'):
                filenames = QtGui.QFileDialog.getOpenFileNames(self, 'Select Files to add to the Queue', self.appConfig['inputFolder'], "Video Files (*.avi *.mp4 *.mkv *.ogm)")
            else:
                filenames = QtGui.QFileDialog.getOpenFileNames(self, 'Select Files to add to the Queue', self.appConfig['inputFolder'], "Audio Files (*.mp3 *.aac *.m4a *.ogg)")
            
        else:
            filenames = []
        
        if(len(filenames)):
            self.addFilesToQueue(filenames)
        
    def addFilesToQueue(self, filenames):
        items = []
        for file in filenames:
            item = QueueItem(file)
            items.append(item)
        
        if(len(items)):
            self.activeQueue.addItems(items)
            self.updateQueueInGui(self.activeGuiQueue, self.activeQueue)
        
    def slotRemoveFilesFromQueue(self):
        
        if self.activeGuiQueue != None and self.activeQueue != None:
            indexes = self.activeGuiQueue.selectedIndexes()
            toRemove = []
            vals = self.activeQueue.vals()
            for index in indexes:
                realID = vals[index.row()]
                if(realID not in toRemove):
                    toRemove.append(realID)
            self.activeQueue.removeItems(toRemove)
            self.updateQueueInGui(self.activeGuiQueue, self.activeQueue)
            
    def slotRemoveAll(self):
		if(self.vidQueue.length() != 0):
			self.vidQueue.removeAll()
			self.updateQueueInGui(self.ui.queue_Video, self.vidQueue)
		if(self.audQueue.length() != 0):
			self.audQueue.removeAll()
			self.updateQueueInGui(self.ui.queue_Audio, self.audQueue)
        
        
    def slotAddFolder(self):
        if(self.ui.tabWidget_Queue.currentIndex() == 0 and self.ui.queue_Video.isEnabled()):
            self.activeQueue = self.vidQueue
            self.activeGuiQueue = self.ui.queue_Video
            folder = QtGui.QFileDialog.getExistingDirectory(self, 'Select Folder from which files will be to add to the Queue', self.appConfig['inputFolder'], QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks)
        elif(self.ui.tabWidget_Queue.currentIndex() == 1 and self.ui.queue_Audio.isEnabled()):
            self.activeQueue = self.audQueue
            self.activeGuiQueue = self.ui.queue_Audio
            folder = QtGui.QFileDialog.getExistingDirectory(self, 'Select Folder from which files will be to add to the Queue', self.appConfig['inputFolder'], QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks)
        else:
            folder = ''
        
        files = []
        
        if(folder != ''):
            files = os.listdir(folder)
        
        foundFiles = []
        
        for x in range(0, len(files)):
            temp = os.path.join(str(folder), files[x]).replace('\\', '/')
            if(os.path.isfile(temp)):
                s = temp.split('.')
                if(self.activeQueue == self.audQueue):
                    if(self.converterMode == 'audioExtractor' and s[len(s) - 1] in '*.avi *.mp4 *.mkv *.ogm'):
                        foundFiles.append(temp)  
                    elif(s[len(s) - 1] in '*.mp3 *.aac *.m4a *.ogg'):
                        foundFiles.append(temp)
                elif(self.activeQueue == self.vidQueue):
                    if(s[len(s) - 1] in '*.avi *.mp4 *.mkv *.ogm'):
                        foundFiles.append(temp)                    
            
        self.addFilesToQueue(foundFiles)
    
    def updateQueueInGui(self, guiQueue, queue):

        #queue.setEditTriggers(QtGui.QTableWidget.DoubleClicked | QtGui.QTableWidget.AnyKeyPressed | QtGui.QTableWidget.EditKeyPressed)
        guiQueue.clearContents()
        count = 0;
        for id in queue.vals():
            item = queue.getItem(id)
            tempFile = QtGui.QTableWidgetItem(item.inputUrl)
            tempStatus = QtGui.QTableWidgetItem(item.status)
            guiQueue.insertRow(count)
            guiQueue.setItem(count, 1, tempFile)
            guiQueue.setItem(count, 0, tempStatus)
            count += 1
        guiQueue.setRowCount(queue.length())

    def slotChooseMode(self):
        if(self.ui.videoMode.isChecked()):
            val = self.ui.videoModeOperation.currentIndex()
            if(val == 0):
                self.converterMode = 'muxer'
            elif(val == 1):
                self.converterMode = 'remuxer'
            elif(val == 2):
                self.converterMode = 'videoExtractor'
            elif(val == 3):
                self.converterMode = 'convertToMkv'
            else:
                self.converterMode = ''

        elif(self.ui.audioMode.isChecked()):
            val = self.ui.audioModeOperation.currentIndex()
            if(val == 0):
                self.converterMode = 'audioExtractor'
            elif(val == 1):
                self.converterMode = 'audioReplacer'
            else:
                self.converterMode = ''
    
    def slotStartConversion(self):
        if self.activeQueue != None:
            for id in self.activeQueue.vals():
                item = self.activeQueue.getItem(id)
                item.resetStatus()
                self.activeQueue.updateItem(id, item)
            
            self.updateQueueInGui(self.activeGuiQueue, self.activeQueue)
            self.ui.totalProgress.setValue(0)
            
            self.instanceArgs['audio_track'] = str(self.ui.audioTrackID.value())
            self.instanceArgs['change_fps'] = self.ui.changeFps.isChecked()
            self.instanceArgs['fps'] = str(self.ui.fpsValue.value())
            self.instanceArgs['inputAudioLang'] = str(self.ui.langaugeSelect.currentText())
            self.instanceArgs['replacementAudioPath'] = ''
            self.instanceArgs['video_track'] = str(self.ui.videoTrackID.value())
            self.instanceArgs['audio_track'] = str(self.ui.audioTrackID.value())
            self.instanceArgs['title'] = self.appConfig['title']
            
            if(self.slotDefaultOutput()):
                self.totalJobs = self.activeQueue.length()
                self.currentJob = 0
                if(self.totalJobs != 0):
                    self.jobID = self.activeQueue.vals()[self.currentJob]
                    self.startConversion(self.jobID)
            elif(self.slotCustomOutput()):
                self.totalJobs = self.activeQueue.length()
                self.currentJob = 0
                if(self.totalJobs != 0):
                    self.jobID = self.activeQueue.vals()[self.currentJob]
                    self.startConversion(self.jobID)
            
    
    def processNextJob(self):
        if(not self.abortFlag):
            self.currentJob += 1
            if(self.currentJob < self.totalJobs):
                self.jobID = self.activeQueue.vals()[self.currentJob]
                self.preJobOperations()
                self.startConversion(self.jobID)
            else:
                self.endJobProcessing()
        else:
            self.endJobProcessing()
        
    def endJobProcessing(self):
        self.clearAbortFlag()
        self.unfreezeGuiElements()
        self.stopTimer()
        self.resetTimes()
        self.processedJobs = 0
        print 'finished processing jobs'
    
    def extractExt(self, name):
        ind = str(name).rfind('.')
        if(ind != -1):
            return name[ind + 1:]
        else:
            return None
    
    def extError(self):
        result = QtGui.QMessageBox.Critical(self, 'Unidentified Type', 'File: ' + self.instanceArgs['inputPath'] + ' does not appear to have a valid extension\nDo you still wish to process this file?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if(result == QtGui.QMessageBox.Yes):
            return True
        else:
            return False
    
    def startConversion(self, id):
        ext = ''
        if(self.converterMode == 'audioExtractor' or self.converterMode == 'videoExtractor' or self.converterMode == 'remuxer' or self.converterMode == 'convertToMkv'):
            self.instanceArgs['inputPath'] = self.activeQueue.getItem(id).inputUrl
            self.instanceArgs['outputPath'] = self.activeQueue.getItem(id).outputUrl
            self.instanceArgs['outputPath'] = self.activeQueue.getItem(id).outputUrl
            if(self.converterMode == 'convertToMkv'):
                self.instanceArgs['outputPath'] = self.activeQueue.getItem(id).outputUrl.replace(".avi", ".mkv").replace(".ogm", ".mkv").replace(".mp4", ".mkv")
                ext = self.extractExt(self.instanceArgs['inputPath'])
                if(not (ext == 'avi' or ext == 'mp4' or ext == 'ogm')):
                    if(not self.extError()):
                        self.setAbortFlag()
        elif(self.converterMode == 'muxer' or self.converterMode == 'audioReplacer'):
            self.instanceArgs['inputAudioPath'] = self.audQueue.getItem(id).inputUrl
            self.instanceArgs['inputVideoPath'] = self.vidQueue.getItem(id).inputUrl
            self.instanceArgs['outputPath'] = self.vidQueue.getItem(id).outputUrl
        
        self.ui.processing.setText(str(self.currentJob + 1) + '/' + str(self.totalJobs))
        
        if(os.path.exists(os.path.abspath(self.instanceArgs['outputPath']))):
            self.stopTimer()
            result = QtGui.QMessageBox.warning(self, 'Conflict', 'File: ' + str(self.instanceArgs['outputPath']) + ' already Exists\nDo You want to overwrite?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if(result == QtGui.QMessageBox.Yes):
                if(ext == 'avi' or ext == 'ogm'):
                    self.vidUtil.setmode('aviToMkv')
                elif(ext == 'mp4'):
                    self.vidUtil.setmode('mp4ToMkv')
                else:
                    self.vidUtil.setmode(self.converterMode)
                self.preJobOperations()
                self.freezeGuiElements()
                if(not self.Timer.isActive()):
                    self.startTimer()
                self.vidUtil.convert(self.instanceArgs)
            else:
                self.freezeGuiElements()
                self.skipJoboperations()
        else:
            print 'converting'
            if(ext == 'avi' or ext == 'ogm'):
                self.vidUtil.setmode('aviToMkv')
            elif(ext == 'mp4'):
                self.vidUtil.setmode('mp4ToMkv')
            else:
                self.vidUtil.setmode(self.converterMode)
            self.preJobOperations()
            self.freezeGuiElements()
            if(not self.Timer.isActive()):
                    self.startTimer()
            self.vidUtil.convert(self.instanceArgs)
            print self.vidUtil.errorCode()
    
    def setAbortFlag(self):
        self.abortFlag = True
    
    def clearAbortFlag(self):
        self.abortFlag = False
        
    def freezeGuiElements(self):
        self.setGuiStatus(True)
        
    def unfreezeGuiElements(self):
        self.setGuiStatus(False)
    
    def setGuiStatus(self, status):
        self.ui.queueOperationsGroup.setDisabled(status)
        self.ui.defaultFolders.setDisabled(status)
        self.ui.modeGroup.setDisabled(status)
        self.ui.outputFolder.setDisabled(status)
        self.ui.startBatch.setDisabled(status)
        
    def slotCustomOutput(self):
        folder = QtGui.QFileDialog.getExistingDirectory(self, 'Select Folder to which files will be saved', self.appConfig['outputFolder'], QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks)
        if(folder != ''):
            self.ui.defaultFolders.setChecked(False)
            self.output = str(folder)
            self.setOutput()
            return True
        else:
            return False
                
    def slotDefaultOutput(self):
        if(self.ui.defaultFolders.isChecked()):
            self.output = self.appConfig['outputFolder']
            self.setOutput()
            return True
        else:
            return False
    
    def setOutput(self):
        temp = {}
        if self.vidQueue != None:
            for id in self.vidQueue.vals():
                item = self.vidQueue.getItem(id)
                if(self.converterMode == 'audioExtractor'):
                    item.setExt(str(self.ui.audExt.currentText()))
                item.setOutputPath(self.output)
                temp[id] = item
            self.vidQueue.updateQueue(temp)
        if self.audQueue != None:
            for id in self.audQueue.vals():
                item = self.audQueue.getItem(id)
                if(self.converterMode == 'audioExtractor'):
                    item.setExt(str(self.ui.audExt.currentText()))
                item.setOutputPath(self.output)
                temp[id] = item
            self.audQueue.updateQueue(temp)
            
            
    def preJobOperations(self):
        self.setItemStatus(self.jobID, 'pre')
        self.setRowColor(self.currentJob)
    
    def postJobOperations(self):
        self.setItemStatus(self.jobID, 'post')
        self.updateGuiAfterJob()
        self.slotCalculateEstimatedTime()
        self.processNextJob()
        
    def skipJoboperations(self):
        self.setItemStatus(self.jobID, 'skip')
        self.updateGuiAfterJob()
        self.slotCalculateEstimatedTime()
        self.processNextJob()
        
    def setItemStatus(self, id, key):
        item = self.activeQueue.getItem(id)
        
        if key == 'post':
            if(self.vidUtil.completed()):
                if(self.vidUtil.success()):
                    item.status = "Success"
                    item.backgroundColor = 'green'
                    self.processedJobs += 1
                else:
                    item.status = 'Failed'
                    item.backgroundColor = 'red'
            
        elif key == 'pre':
            item.status = 'Processing'
            item.backgroundColor = 'yellow'
            
        elif key == 'skip':
            item.status = 'Skipped'
            item.backgroundColor = 'orange'
        
        self.activeQueue.updateItem(id, item)
        
    
    def updateGuiAfterJob(self):
        
        #statistics updation
        self.ui.processing.setText(str(self.currentJob + 1) + '/' + str(self.totalJobs))
        
        #queue view updation
        self.setRowColor(self.currentJob)
        
        #progress indicator updation
        self.ui.totalProgress.setValue(((self.currentJob + 1) * 100) / self.totalJobs)
        
    def setRowColor(self, row):
        self.jobID = self.activeQueue.vals()[row]
        item = self.activeQueue.getItem(self.jobID)
        tempStatus = QtGui.QTableWidgetItem(item.status)
        tempFile = QtGui.QTableWidgetItem(item.inputUrl)
        
        tempFile.setBackgroundColor(QtGui.QColor(item.backgroundColor))
        tempStatus.setBackgroundColor(QtGui.QColor(item.backgroundColor))

        self.activeGuiQueue.setItem(row, 0, tempStatus)
        self.activeGuiQueue.setItem(row, 1, tempFile)

    def slotChangeAppConfig(self):
        if(self.settings == None):
            self.settings = Settings(self)
            r = self.settings.geometry()
            r.moveCenter(QtGui.QApplication.desktop().availableGeometry().center())
            self.settings.setGeometry(r)
        self.settings.setModal(True)
        self.settings.show()
        
    def slotShowAboutPyBatch(self):
        if(self.aboutPyBatch == None):
            self.aboutPyBatch = AboutPyBatch(None,)
            r = self.aboutPyBatch .geometry()
            r.moveCenter(QtGui.QApplication.desktop().availableGeometry().center())
            self.aboutPyBatch .setGeometry(r)
        self.aboutPyBatch.setModal(True)
        self.aboutPyBatch.show()
        
    def startTimer(self):
        self.Timer.start(1000)
        
    def slotUpdateElapsedtime(self):
        self.elapsedTime = self.elapsedTime.addSecs(1)
        self.ui.elapsedTime.setText(self.elapsedTime.toString())
        
    def stopTimer(self):
        self.Timer.stop()
        
    def resetTimes(self):
        self.elapsedTime = QtCore.QTime(0, 0, 0, 0)
        self.estimatedTime = QtCore.QTime(0, 0, 0, 0)
        
    def slotUpdateEstimatedTime(self):
        if(self.processedJobs == 0):
            self.ui.estimatedTime.setText("estimating..")
        else:
            self.estimatedTime = self.estimatedTime.addSecs(-1)
            if(self.estimatedTime.hour() < 23):
                self.ui.estimatedTime.setText(self.estimatedTime.toString())
        
    def slotCalculateEstimatedTime(self):
        tillNow = self.elapsedTime.second() + self.elapsedTime.minute()*60 + self.elapsedTime.hour()*3600
        average = float(tillNow) / float(self.currentJob + 1)
        estimate = int((self.totalJobs - self.currentJob) * average)
        hrs = estimate / 3600
        min = (estimate % 3600) / 60
        sec = ((estimate % 3600) % 60)
        self.estimatedTime = QtCore.QTime(hrs, min, sec, 0)
        
        
    def fileDragEnterEvent(self, event):
             event.accept() 

    def fileDropEvent(self, event):
        link=event.mimeData().text()
        print link 
        event.accept()
